package com.zhy.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zhy.usercenter.auth.DbmAuthority;
import com.zhy.usercenter.common.BaseResponse;
import com.zhy.usercenter.common.ErrorCode;
import com.zhy.usercenter.common.ResultUtils;
import com.zhy.usercenter.entity.User;
import com.zhy.usercenter.entity.UserLogin;
import com.zhy.usercenter.entity.UserRegister;
import com.zhy.usercenter.exception.BusinessException;
import com.zhy.usercenter.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.util.List;
import java.util.stream.Collectors;

import static com.zhy.usercenter.constant.UserConstant.*;

/**
 * @author 随缘而愈
 * @version 2.0
 * @description 用户中心控制层
 * @date 21/2/2024 下午2:58
 */
@Api(tags = "用户中心")
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     *
     * @param userRegister      用户注册实体类
     * @return                  自定义返回类型
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册",notes = "用户数据")
    public BaseResponse<Long> userRegister(@RequestBody UserRegister userRegister) {
        // 校验
        if (userRegister == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegister.getUserAccount();
        String userPassword = userRegister.getUserPassword();
        String rePassword = userRegister.getRePassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, rePassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, rePassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLogin     用户登录实体类
     * @param request       请求
     * @return              自定义返回类型
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户数据")
    public BaseResponse<User> userLogin(@RequestBody UserLogin userLogin, HttpServletRequest request) {
        if (userLogin == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLogin.getUserAccount();
        String userPassword = userLogin.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request   请求
     * @return          自定义返回类型
     */
    @PostMapping("/logout")
    @ApiOperation(value = "用户注销", notes = "请求")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户
     *
     * @param request    请求
     * @return           统一返回类型
     */
    @GetMapping("/current")
    @ApiOperation(value = "获取当前用户", notes = "请求")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        // TODO 校验用户是否合法
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    /**
     * 查询用户（管理员）
     * @param username   用户昵称
     * @param request    请求
     * @return           所有用户信息
     */
    @GetMapping("/search")
    @ApiOperation(value = "查询所有用户", notes = "用户昵称&请求")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    /**
     * 删除用户（管理员）
     * @param id        用户id
     * @param request   请求
     * @return          是否成功
    */
    @PostMapping("/delete")
    @ApiOperation(value = "删除用户", notes = "用户id&请求")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新用户（管理员）
     * @param user       用户
     * @param request   请求
     * @return          是否成功
     */
    @DbmAuthority("功能:角色:权限") //访问这个功能登录用户所需要的角色和权限
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody User user,HttpServletRequest request){
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (user.getId() <=0 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //TODO 用户行为记录
        Long userId = user.getId();
        // 获取请求的URL
        String requestUrl = request.getRequestURL().toString();
        // 记录用户行为到日志或数据库
        log.info("User {} performed action at {}", userId, requestUrl);


        boolean result = userService.update(user);
        return ResultUtils.success(result);
    }

    /**
     * 是否为管理员
     *
     * @param request   请求
     * @return          是否成功
     */
    private boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
        // TODO 后期优化

    }

    /**
     * 是否为超级管理员
     *
     * @param request   请求
     * @return          是否成功
     */
    private boolean isTopAdmin(HttpServletRequest request) {
        // 仅超级管理员可操作
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == TOP_ADMIN_ROLE;
    }

}
